from django.contrib.admin.views.decorators import staff_member_required
from django.views.decorators.cache import never_cache
from django.shortcuts import render_to_response
from django.template import RequestContext
import utils
from settings import LANGUAGE_PATH
from django.http import Http404
from django import forms
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

#------------------------------------------------------------------------------

@never_cache
@staff_member_required
def list_languages(request):
    l = utils.LanguageFile(LANGUAGE_PATH)
    return render_to_response('list.html',{'languages':l.list_languages()},RequestContext(request))

#------------------------------------------------------------------------------
    
@never_cache
@staff_member_required
def view_language(request, language_code):
    l = utils.LanguageFile(LANGUAGE_PATH)
    language_name = l.get_language_name(language_code)
    codes = l.load_django_po(language_code)
    return render_to_response('view.html',{'language_name':language_name,
                                           'language_code':language_code,
                                           'codes':codes},RequestContext(request))

#------------------------------------------------------------------------------

class LanguageForm(forms.Form):
    translate = forms.CharField(widget=forms.Textarea(attrs={'readonly':'readonly'}), required=False)
    to = forms.CharField(widget=forms.Textarea, required=False)
    
#------------------------------------------------------------------------------
    
@never_cache
@staff_member_required
def edit_language(request, language_code, line_number):
    l = utils.LanguageFile(LANGUAGE_PATH)
    language_name = l.get_language_name(language_code)
    codes = l.load_django_po(language_code,int(line_number))
    if len(codes) == 0:
        raise Http404
    if request.method == 'POST':
        form = LanguageForm(request.POST)
        if form.is_valid():
            msgstr = form.cleaned_data['to']
            if msgstr != codes[0]['msgstr']:
                l.write_django_po(language_code, {int(line_number):msgstr})
            return HttpResponseRedirect(reverse('view_language', kwargs= {'language_code':language_code})+'#'+line_number)
            
    else:
        form = LanguageForm(initial={'translate':codes[0]['msgid'],'to': codes[0]['msgstr']})
    return render_to_response('form.html',{'language_name':language_name,
                                           'language_code':language_code,
                                           'line_number':line_number,
                                           'form':form,
                                           'current_block':codes[0],
                                           'codes':codes},RequestContext(request))